﻿using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication3.Data.Entities;

namespace WebApplication3.Data
{
	public class MyDataContexSeed
	{

		public static async Task SeedAsync(ApplicationDbContext myDataContex,
			ILoggerFactory loggerFactory, int? retry = 0)
		{
			int retryForAvailability = retry.Value;
			try
			{
				// TODO: Only run this if using a real database
				// context.Database.Migrate();

				if (!myDataContex.Roles.Any())
				{
					//await myDataContex.SaveChangesAsync();
				}


			}
			catch (Exception ex)
			{
				if (retryForAvailability < 10)
				{
					retryForAvailability++;
					var log = loggerFactory.CreateLogger<MyDataContexSeed>();
					log.LogError(ex.Message);
					await SeedAsync(myDataContex, loggerFactory, retryForAvailability);
				}
			}
		}

	}

	public class AppIdentityDbContextSeed
	{
		public static async Task SeedAsync(
			UserManager<AppIdentityUser> userManager,
			RoleManager<AppIdentityRole> roleManager, ILoggerFactory loggerFactory, int? retry = 0)
		{
			int retryForAvailability = retry.Value;
			try
			{
				var defaultUser = new AppIdentityUser { OpenId = "admin", UserName = "admin", Email = "admin@wx.com" };
				await userManager.CreateAsync(defaultUser, "Pass@word1");

				await roleManager.CreateAsync(new AppIdentityRole
				{
					Name = "管理员",
				});
				await roleManager.CreateAsync(new AppIdentityRole
				{
					Name = "快递员",
				});

				await roleManager.CreateAsync(new AppIdentityRole
				{
					Name = "客户",
				});

				var admin = await userManager.FindByNameAsync("admin");

				var addToAdmin = await userManager.AddToRoleAsync(admin, "管理员");

			}
			catch (Exception ex)
			{
				if (retryForAvailability < 10)
				{
					retryForAvailability++;
					var log = loggerFactory.CreateLogger<MyDataContexSeed>();
					log.LogError(ex.Message);
					await SeedAsync(userManager, roleManager, loggerFactory, retryForAvailability);
				}
			}

		}
	}
}
